'use strict';

const Controller  = require('egg').Controller;

const loginRule = {
    code:'string',
};


class UserController extends Controller{   
    async login( ){
        const ctx = this.ctx;
        ctx.validate(loginRule, ctx.request.body);
        var code = ctx.request.body.code;
        const {errno, errmsg, data} = await ctx.service.weixin.login(code);
        console.log(errno);
        ctx.status = 200;
        if(errno !== 0) {

            ctx.body={
                errno:errno,
                errmsg:errmsg,
            }
            return ;
        } 
        var id = 0;
        //先查找是不是数据库有数据
        const res = await ctx.service.user.getUseridByOpenid(data.openid);
        console.log(res);
        if(res == null)
        {
            //如果没有用户信息  则新建用户信息
            var myDate = new Date();
            //操纵数据库  存储数据
            var createRes = await ctx.service.user.create(
                {
                    username:"",
                    password:"",
                    gender:0,
                    birthday:0,
                    register_time:myDate.getTime()/1000,
                    last_login_time:myDate.getTime()/1000,
                    last_login_ip:this.ctx.request.ip,
                    register_ip:this.ctx.request.ip,
                    nickname:"",
                    phonenumber:"",
                    avatar:"",
                    weixin_openid:data.openid,
                }
            );
            console.log('---------------------------craete');
            console.log(createRes);
            console.log('---------------------------');
            id = createRes.id;
        }else{
            id = res.id;
            var myDate = new Date();
            //如果有了 则刷新信息
            res.last_login_time = myDate.getTime()/1000;
            res.last_login_ip = ctx.request.ip;
            var updateRes = await ctx.service.user.update(res);
            console.log('---------------------------update');
            console.log(updateRes);
            console.log('---------------------------');
        }


           
        console.log('---------------------------id');
        console.log(id);
        console.log('---------------------------'); 
        //生成token
        var token = await this.service.token.create({user_id: data.openid});
        //获取车辆信息
        var cars = await ctx.service.car.getCar({owner: data.openid});

        ctx.body={
            errno:0,
            data:{token:token,
                cars:cars},
        }
    }
}

module.exports = UserController;
